<?php

namespace App\Http\Middleware;

use Closure;

/**
 * Class RouteNeedsRole
 * @package App\Http\Middleware
 */
class RouteNeedsPermission
{

	/**
     * @param $request
     * @param Closure $next
     * @param $permission
     * @param bool $needsAll
     * @return mixed
     */
    public function handle($request, Closure $next, $permission, $needsAll = false)
    {
        /**
         * Permission array
         */
        if (strpos($permission, ";") !== false) {
            $permissions = explode(";", $permission);

            $access = access()->allowMultiple($permissions, ($needsAll === "true" ? true : false));
        } else {

            /**
             * Single permission
             */
            $access = access()->allow($permission);
        }
// dd($permission);
        //no permission
        if (! $access) {
            //ajax request
            if ($request->ajax()){
                return response()->json(['code'=>403,'msg'=>'没有权限']);
            } else {
                abort(501,'没有权限');

            }
        }

        return $next($request);
    }
}
